package com.erp.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.erp.user.domain.ErpDistributionUser;
import com.erp.user.domain.ErpDistributionUserBasicInfo;
import com.erp.user.domain.bo.ErpDistributionUserBo;
import com.erp.user.domain.param.DistributionParam;
import com.erp.user.domain.vo.ErpDistributionUserVo;
import com.erp.user.mapper.ErpDistributionUserBasicInfoMapper;
import com.erp.user.mapper.ErpDistributionUserMapper;
import com.erp.user.service.IErpDistributionUserBasicInfoService;
import com.erp.user.service.IErpDistributionUserService;
import com.ruoyi.common.core.annotation.RepeatSubmit;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.SpringUtils;
import com.ruoyi.common.core.web.oldController.BaseController;
import com.ruoyi.common.core.web.oldPage.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.RemoteDeptService;
import com.ruoyi.system.api.RemoteSysConfigService;
import com.ruoyi.system.api.RemoteUserService;
import com.ruoyi.system.api.domain.SysDept;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.model.LoginUser;
import com.ruoyi.wallet.api.RemoteWalletService;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.util.*;

/**
 * 市级合伙人
 *
 * @author erp
 * @date 2023-05-08
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/distribution/city")
public class ErpBranchOfficeInfoController extends BaseController {

    private final RemoteUserService remoteUserService;
    private final RemoteWalletService remoteWalletService;
    private final RemoteDeptService remoteDeptService;
    private final RemoteSysConfigService configService;
    private final ErpDistributionUserMapper distributionUserMapper;
    private final IErpDistributionUserService distributionUserService;
    @Resource
    RabbitTemplate rabbitTemplate = SpringUtils.getBean(RabbitTemplate.class);
    @Resource
    IErpDistributionUserBasicInfoService distributionUserBasicInfoService;
    @Resource
    ErpDistributionUserBasicInfoMapper distributionUserBasicInfoMapper;

    /**
     * 查询分公司销售名额 TODO 重新梳理，因为ERP版本有变动，不能简单的设置分销或不分销
     */
//    @GetMapping("/selectOfficeLimit")
//    public List<ErpBranchOfficeInfo> selectOfficeLimit(String code) {
//        ErpBranchOfficeInfo branchOfficeInfo = new ErpBranchOfficeInfo();
//        branchOfficeInfo.setCode(code);
//        return iErpBranchOfficeInfoService.selectOfficeLimit(branchOfficeInfo);
//    }

    /**
     * @Description: 查询分公司开户信息列表
     * @Author: j.zh
     * @Date: 2024/5/2
     * @param bo
     * @param pageQuery
     * @return
     * @Version: 4.0.0
    **/
    @GetMapping("/list")
    public TableDataInfo<ErpDistributionUserVo> list(ErpDistributionUserBo bo, PageQuery pageQuery) {
        bo.setType(1);
        return distributionUserService.queryPageList(bo, pageQuery);
    }

    /**
     * @Description: 查询所有分公司名称、分销码、ID
     * @Author: j.zh
     * @Date: 2024/6/24
     * @return
     * @Version: 4.2.0
    **/
    @GetMapping("/getBranch")
    public List<Object> getBranch() {
        List<Object> list = new ArrayList<>();
        List<ErpDistributionUser> erpAgentInfos = distributionUserService.getListByDistributionUserType(1);
        if (erpAgentInfos != null) {
            erpAgentInfos.forEach(vo -> {
                Map<String, Object> map = new HashMap<>();
                Long id = vo.getDistributionUserId();
                String corporateName = distributionUserBasicInfoService.getByDistributionUserId(vo.getDistributionUserId()).getCorporateName()
                        + "  " + vo.getIdentityCode();
                map.put("label", corporateName);
                map.put("value", id);
                list.add(map);
            });
        }
        return list;
    }

    /**
     * 根据userId查询该用户属于哪个分公司
     */
    @GetMapping("/getBreachByUserId")
    public Map<String,List<Map<String,Object>>> getBreachByUserId() {
        Long userId = SecurityUtils.getUserId();
        Long branchId = 0L;
        List<Map<String,Object>> totalList = new ArrayList<>();
        Map<String, List<Map<String,Object>>> stringMapHashMap = new HashMap<>();
        ErpDistributionUser officeInfo = distributionUserMapper.selectOne(new LambdaQueryWrapper<ErpDistributionUser>()
                .eq(ErpDistributionUser::getUserId, userId));
        if (officeInfo != null) {
            Map<String, Object> map = new HashMap<>();
            branchId = officeInfo.getDistributionUserId();
            map.put("label",distributionUserBasicInfoService.getByDistributionUserId(officeInfo.getDistributionUserId()).getCorporateName());
            map.put("value",officeInfo.getDistributionUserId());
            totalList.add(map);
            stringMapHashMap.put("branch",totalList);
        }else {
            branchId = null;
        }
        List<ErpDistributionUser> agentInfoList = distributionUserMapper.selectList(new LambdaQueryWrapper<ErpDistributionUser>()
                .eq(ErpDistributionUser::getParentBranchId, branchId));
        totalList = new ArrayList<>();
        for (ErpDistributionUser agentInfo : agentInfoList) {
            Long userId1 = agentInfo.getUserId();
            R<Object> objectR = remoteUserService.selectUserById(userId1);
            String data = JSONObject.toJSONString(objectR.getData());
            SysUser sysUser = JSONObject.parseObject(data, SysUser.class);
            Map<String, Object> map = new HashMap<>();
            map.put("label",sysUser.getUserName() + " " + distributionUserBasicInfoService.getByDistributionUserId(agentInfo.getDistributionUserId()).getRealName()
                    + " " + agentInfo.getIdentityCode());
            map.put("value",agentInfo.getDistributionUserId());
            totalList.add(map);
            stringMapHashMap.put("agent",totalList);
        }
        List<ErpDistributionUser> erpUserInfos = distributionUserMapper.selectList(new LambdaQueryWrapper<ErpDistributionUser>()
                .eq(ErpDistributionUser::getParentBranchId, branchId).isNull(ErpDistributionUser::getParentAgentId));
        totalList = new ArrayList<>();
        for (ErpDistributionUser erpUserInfo : erpUserInfos) {
            Map<String, Object> map = new HashMap<>();
            map.put("label",distributionUserBasicInfoService.getByDistributionUserId(erpUserInfo.getDistributionUserId()).getRealName()
                    + erpUserInfo.getIdentityCode());
            map.put("value",erpUserInfo.getDistributionUserId());

            totalList.add(map);
            stringMapHashMap.put("user",totalList);
        }
        return stringMapHashMap;
    }


    /**
     * 查询分公司,代理
     */
    @GetMapping("/getBranchAndAgent")
    public List<ErpDistributionUserVo> getBranchAndAgent() {
        return distributionUserService.queryPageBranchAndAgent();
    }

    /**
     * 查询分公司,代理,个人
     */
    @GetMapping("/getBranchAndAgentUser")
    public List<ErpDistributionUserVo> getBranchAndAgentUser() {
        return distributionUserService.queryPageBranchAndAgentUser();
    }

    /**
     * 导出分公司开户信息列表
     */
//    @SaCheckPermission("system:branchOfficeInfo:export")
//    @Log(title = "分公司开户信息", businessType = BusinessType.EXPORT)
//    @PostMapping("/export")
//    public void export(ErpBranchOfficeInfoBo bo, HttpServletResponse response) {
//        List<ErpBranchOfficeInfoVo> list = iErpBranchOfficeInfoService.queryList(bo);
////        ExcelUtil.exportExcel(list, "分公司开户信息", ErpBranchOfficeInfoVo.class, response);
//    }

    /**
     * @Description: 根据DistributionUserId获取分公司开户信息详细信息
     * @Author: j.zh
     * @Date: 2024/6/25
     * @param id
     * @return
     * @Version: 4.2.0
    **/
    @GetMapping("/{id}")
    public R<ErpDistributionUserVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long id) {
        return R.ok(distributionUserMapper.selectVoByDistributionId(id));
    }

    /**
     * 新增市级合伙人开户信息
     */
    @Log(title = "分公司开户信息", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @Transactional
    @PostMapping("/add")
    public R<Void> add(@RequestBody DistributionParam param) {
        /** 注册系统用户 **/
        // 获取注册信息
        SysUser user = param.getUser();
        // 创建新部门
        SysDept sysDept = new SysDept();
        // 部门公共信息
        sysDept.setDeptName(param.getDistributionUserBasicInfo().getCorporateName());
        sysDept.setEmail(user.getEmail());
        sysDept.setLeader(param.getDistributionUserBasicInfo().getLegalPerson());
        sysDept.setPhone(user.getPhonenumber());
        // 分公司只能在总公司下创建部门
        sysDept.setParentId(101L);
        sysDept.setOrderNum(0);
        R<Object> insert = remoteDeptService.insert(sysDept, SecurityConstants.INNER);
        if (insert.getCode() != 200)
            return R.fail(insert.getMsg());
        Long deptId = remoteDeptService.searchByDeptName(param.getDistributionUserBasicInfo().getCorporateName());
        // 为新用户分配部门
        user.setDeptId(deptId);
        // 为新用户分配角色：分公司
        user.setRoleIds(new Long[]{1656968008241926145L});
        user.setNickName(sysDept.getDeptName());
        // 注册系统用户
        remoteUserService.registerUser(user, SecurityConstants.INNER);
        R<LoginUser> userInfo = remoteUserService.getUserInfo(user.getUserName(), SecurityConstants.INNER);
        if (userInfo.getData() == null) {
            throw new RuntimeException("获取用户失败");
        }
        Long userId = userInfo.getData().getSysUser().getUserId();


        /** 注册分销用户 **/
        // 获取注册分销用户所需信息
        ErpDistributionUser distributionUser = param.getDistributionUser();


        ErpDistributionUser parentDistributionUser = null;
        if(distributionUser.getParentId() == null){
            return R.fail("推荐人获取失败，请联系管理员");
        }
        // 获取到上级的父类ids
        parentDistributionUser = distributionUserService.getDistributionUserById(distributionUser.getParentId());
        String parentIds = parentDistributionUser.getParentIds();
        if (parentIds.equals("0")) {
            // 说明是总公司推荐
            distributionUser.setParentIds("1");
        }else {
            distributionUser.setParentIds(parentIds + "," + distributionUser.getParentId().toString());
        }

        distributionUser.setUserId(userId);
        // 生成身份代码
        distributionUser.setIdentityCode(distributionUserService.createIdentityCode(1));
        // 生成邀请码
        distributionUser.setInvitationCode(distributionUserService.createInvitationCode());
        // 分销员类型：分公司
        distributionUser.setType(1);
        // 状态：正常
        distributionUser.setState(1);
        // 绑定时间
        distributionUser.setBindTime(new Date());
        // 格式化管理城市
        distributionUser.setManageCity(distributionUser.getManageCity().replaceAll("\"", "").replaceAll("\\\\", ""));
        // 注册分销员
        Long distributionId = distributionUserService.insertDistributionUser(distributionUser);
        // 保存分销员基本信息
        ErpDistributionUserBasicInfo userBasicInfo = param.getDistributionUserBasicInfo();
        userBasicInfo.setDistributionUserId(distributionId);
        distributionUserBasicInfoMapper.insert(userBasicInfo);

        // 初始化钱包
        remoteWalletService.initWallet(distributionId, userId, SecurityConstants.INNER);


        /** 分销计算 **/
        Map<String, Object> divideMap = new HashMap<>();
        // 分销类型
        divideMap.put("distributionType", 1);
        // 是否分销 TODO 获取不到，暂时写死
//        divideMap.put("isDistribution", param.getIsDistribution());
        divideMap.put("isDistribution", 0);
        // 分销金额
        divideMap.put("distributionAmount", new BigDecimal(configService.getConfigKey("office_amount").getMsg()));
        // 判断分销方式 TODO 自定义分销未做，默认固定方式
        divideMap.put("distributionMode",0);
        // 备注
        divideMap.put("remarks", "分公司：" + distributionId + "-" + param.getDistributionUserBasicInfo().getCorporateName());

        // 分发计算
        rabbitTemplate.convertAndSend("distribution-event-exchange",
                "distribution.sale.system.divide", JSONObject.toJSONString(divideMap));
        return R.ok();
    }

    /**
     * 修改分公司开户信息 TODO 现在用的少，先不着急修改
     */
    @Log(title = "分公司开户信息", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PostMapping("/edit")
    public R<Void> edit(@RequestBody DistributionParam param) {
//        // 获取分公司的用户的手机号
//        List<String> phoneList = new ArrayList<>();
//        List<String> emailList = new ArrayList<>();
//        SysUser user = param.getUser();
//        ErpBranchOfficeInfoBo info = param.getInfo();
//        List<ErpBranchOfficeInfoVo> erpBranchOfficeInfos = branchOfficeInfoMapper.selectVoList(new LambdaQueryWrapper<ErpBranchOfficeInfo>()
//                .ne(ErpBranchOfficeInfo::getUserId,info.getUserId()));
//        for (ErpBranchOfficeInfoVo officeInfo : erpBranchOfficeInfos) {
//            Long userId = officeInfo.getUserId();
//            R<Object> objectR = remoteUserService.selectUserById(userId);
//            String toJSONString = JSONObject.toJSONString(objectR.getData());
//            SysUser sysUser = JSONObject.parseObject(toJSONString, SysUser.class);
//            phoneList.add(sysUser.getPhonenumber());
//            emailList.add(sysUser.getEmail());
//        }
//        user.setUserId(info.getUserId()); // 校验剔除该id
//        String userName = user.getUserName();
////        userService.checkUserAllowed(user);
////        userService.checkUserDataScope(user.getUserId());
////        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user))) {
////            return R.fail("修改用户'" + userName + "'失败，登录账号已存在");
////        } else if (StringUtils.isNotEmpty(user.getPhonenumber())
////                && phoneList.contains(user.getPhonenumber())) {
////            return R.fail("修改用户'" + userName + "'失败，手机号码已存在");
////        } else if (StringUtils.isNotEmpty(user.getEmail())
////                && emailList.contains(user.getEmail())) {
////            return R.fail("修改用户'" + userName + "'失败，邮箱账号已存在");
////        }
//        R<Object> objectR = remoteUserService.selectUserById(info.getUserId());
//        String toJSONString = JSONObject.toJSONString(objectR.getData());
//        SysUser sysUser = JSONObject.parseObject(toJSONString, SysUser.class);
//        sysUser.setUserName(userName);
//        sysUser.setEmail(user.getEmail());
//        sysUser.setPhonenumber(user.getPhonenumber());
//        remoteUserService.updateUser(sysUser);
//
//        // 修改部门名称
//        SysDept dept = sysUser.getDept();
////        SysDept sysDept = deptService.selectDeptById(deptId);
////        sysDept.setDeptName(info.getCorporateName());
////        deptService.updateDept(sysDept);
//
//        return toAjax(iErpBranchOfficeInfoService.updateByBo(info));
        return R.ok();
    }

    /**
     * 删除分公司开户信息 TODO 现在用的少，先不着急修改
     *
     * @param ids 主键串
     */
    @Log(title = "分公司开户信息", businessType = BusinessType.DELETE)
    @GetMapping("/delete")
    @Transactional
    public R<Void> remove(String ids) {
//        List<String> collect = Arrays.stream(ids.split(",")).collect(Collectors.toList());
//        for (String s : collect) {
//            Long id = Long.parseLong(s);
//            ErpBranchOfficeInfoVo infoVo = iErpBranchOfficeInfoService.queryById(id);
//            Long userId = infoVo.getUserId();
//            Long deptId = infoVo.getDeptId();
////            List<SysUser> sysUsers = userMapper.selectList(new LambdaQueryWrapper<SysUser>().eq(SysUser::getDeptId, deptId)
////                    .ne(ObjectUtil.isNotNull(userId), SysUser::getUserId, userId));
////            if (sysUsers != null && sysUsers.size() != 0) {
////                return R.fail("分公司下存在用户,无法删除");
////            }else {
////                deptService.deleteDeptById(deptId);
//            remoteUserService.deleteUserById(userId);
//                branchOfficeInfoMapper.deleteById(id);
////            }
//        }
        return R.ok();
    }

    /**
     * 分公司历史数据推广提成数据重跑
     */
    @GetMapping("/branchInfoRerun")
    public R<String> agentInfoRerun() {
//        List<ErpBranchOfficeInfo> list=branchOfficeInfoMapper.selectList();
//        for (ErpBranchOfficeInfo info:list){
//            if(StringUtils.isEmpty(info.getParentId())){
//                continue;
//            }
//            String parentCode = null; // 推荐人的代码
//            if (StringUtils.isNotEmpty(info.getParentId())) {
//                ErpBranchOfficeInfoVo branchOfficeInfoVo = iErpBranchOfficeInfoService.queryById(Long.parseLong(info.getParentId()));
//                parentCode = branchOfficeInfoVo.getCode();
//            }
//
//            R<Object> configKey = configService.getConfigKey("office_amount");
//            String officeAmount = configKey.getMsg();
//            BigDecimal amount = new BigDecimal(officeAmount);
//            // 4. 访问分销接口
//            /**
//             * 分佣
//             * @param userId        被推广用户id
//             * @param userType      被推广用户类型（1分公司 2代理 3个人）
//             * @param recommendTime 推荐时间
//             * @param parentCode      推荐客户编码
//             * @param amount        金额
//             * @param isDivide      是否分佣 0否 1是
//             * @param orderNo       订单号
//             */
////            distributePropService.divide(info.getUserId(), 1, info.getCreateTime(), parentCode, amount, 0, "G"+(info.getId() + 999));
//        }
        return R.ok();
    }


}
